#include "OgreStableHeaders.h"
#include "OgreCodec.h"
#include "OgreException.h"
#include "OgreStringConverter.h"

namespace Ogre
{
	map<String, Codec*>::type Codec::ms_mapCodecs;

	Codec::~Codec()
	{
	}

	StringVector Codec::getExtensions(void)
	{
		StringVector result;
		result.reserve(ms_mapCodecs.size());
		CodecList::const_iterator i;
		for (i = ms_mapCodecs.begin(); i != ms_mapCodecs.end(); ++i)
		{
			result.push_back(i->first);
		}
		return result;
	}

	Codec* Codec::getCodec(const String& extension)
	{
		String lwrcase = extension;
		StringUtil::toLowerCase(lwrcase);
		CodecList::const_iterator i = ms_mapCodecs.find(lwrcase);
		if (i == ms_mapCodecs.end())
		{
			String formats_str;
			if (ms_mapCodecs.empty())
				formats_str = "There are no formats supported(no codecs registered).";
			else
				formats_str = "Supported formats are: " + StringConverter::toString(getExtensions()) + ".";

			OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND,
				"Can not find codec for '" + extension + "' image format.\n" +
				formats_str,
				"Codec::getCodec");
		}

		return i->second;
	}

	Codec* Codec::getCodec(char* magicNumberPtr, size_t maxbytes)
	{
		for (CodecList::const_iterator i = ms_mapCodecs.begin();
			i != ms_mapCodecs.end(); ++i)
		{
			String ext = i->second->magicNumberToFileExt(magicNumberPtr, maxbytes);

			if (!ext.empty())
			{
				if (ext == i->second->getType())
					return i->second;
				else
					return getCodec(ext);
			}
		}

		return 0;
	}
}
